package com.hanter.downloader.task;

/**
 * 类名：CancelableTask <br/>
 * 描述：可取消的任务
 * 创建时间：2021/10/25 21:45
 *
 * @author hanter
 * @version 1.0
 */
public class CancelableTask implements Runnable {

    private final Runnable runnable;
    private volatile Thread runner;

    protected CancelableTask(Runnable runnable) {
        this.runnable = runnable;
    }

    public void cancel() {
        if (runner != null) {
            synchronized (CancelableTask.class) {
                if (runner != null) {
                    runner.interrupt();
                }
            }
        }
    }

    @Override
    public void run() {
        runner = Thread.currentThread();
        try {
            runnable.run();
        } finally {
            runner = null;
        }
    }

}
